package gocache

import (
	"sync"
	"time"
)

type Table interface {
	Set(key string,value interface{},lifeSpan uint64)error
	Get(key string) interface{}
	Free()
	CheckFree()
	Foreach(fn func(item Item))
}
type myTable struct {
	sync.RWMutex
	items map[string]Item

}

func (this *myTable)Set(key string,value interface{},lifeSpan uint64)error  {
	item := NewItem(key,value,lifeSpan)
	this.Lock()
	defer this.Unlock()
	this.items[key] = item
	return nil
}
func (this *myTable)Get(key string)interface{}  {
	this.RLock()
	defer this.RUnlock()
	item,ok := this.items[key]
	if !ok{
		return nil
	}
	return item.Value()
}
func (this *myTable)Free()  {
		this.Lock()
		defer this.Unlock()
		this.items = map[string]Item{}
}
func(this *myTable)CheckFree(){
	this.Foreach(func(item Item) {
		if item.Expiry() >uint64(time.Now().Unix() + 10) || item.Free()==1{
			delete(this.items,item.Key())
		}
	})
}
func (this *myTable)Foreach(fn func(item Item)) {
	for _,item:= range this.items{
		fn(item)
	}
}
func NewTable()Table  {
	return &myTable{
		items:make(map[string]Item),
	}
}